﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;
using System.Web.Configuration;
using System.Configuration;
using System.Data.SqlClient;

public partial class EduCenterWebsite_AdminVideo : System.Web.UI.Page
{
    string fileType = "";

    protected void Page_PreRender(object sender, EventArgs e)
    {
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!User.IsInRole("adminUploader"))
        {
            Response.Redirect("NoAccess.aspx"); //if user is not logged in, redirect to register screen
        }

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);  //connection string to the container
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); //creates the blob service client
        var properties = blobClient.GetServiceProperties(); //get properties so we can change them
        properties.DefaultServiceVersion = "2012-02-12"; //set to version
        blobClient.SetServiceProperties(properties); //add new properties
        Session["blobClient"] = blobClient;
    }

    protected void AddVideo_Click(object sender, EventArgs e)
    {
        this.PopUpButton_ModalPopupExtender.Show(); //show ajax popup with the upload controls
    }

    protected void DeleteVideo_Click(object sender, EventArgs e)
    {
        string strConnString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; //connection string to database
        SqlConnection Connection = new SqlConnection(strConnString); //set connectionstring to sqlconnection
        Session["ConnDB"] = Connection;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        string SqlQuery; 
        string fileName = deleteVideoBox.Text; //get filename of selected main file
        CloudBlobClient blobClient = (CloudBlobClient)Session["blobClient"];
        CloudBlobContainer container = null;
        CloudBlockBlob blockBlob = null;

        SqlQuery = "SELECT filetype FROM videoTable where name ='" + fileName + "';"; //determine filetype of the input
        SqlCommand cmd = new SqlCommand(SqlQuery, Connection); //establish new sqlcommand
        Connection.Open(); //open connection
        SqlDataReader Reader = cmd.ExecuteReader(); //execture sql command set it to reader
        while (Reader.Read()) //as long as the reader has content , do this
        {
            fileType = Reader[0] as string; //set filetype to string
        }
        if (fileType.Equals("listen")) //if the string from reader is listen, do this
        {
            string deleteMainFile = fileName + ".wma"; //delete the main file
            string deleteHtmlFile = fileName + ".html"; //delete the html file
            container = blobClient.GetContainerReference("audio-container"); //get container
            blockBlob = container.GetBlockBlobReference(deleteMainFile); //get the mainfile blob
            blockBlob.Delete(); //delete the file
            blockBlob = container.GetBlockBlobReference(deleteHtmlFile); //get the html file blob
            blockBlob.Delete(); //delete the file
        }
        else if (fileType.Equals("watch")) //if the string from reader is watch, do this
        {
            string deleteMainFile = fileName + ".wmv"; //delete the main file
            string deleteHtmlFile = fileName + ".html"; //delete the html file
            container = blobClient.GetContainerReference("video-container"); //get container
            blockBlob = container.GetBlockBlobReference(deleteMainFile); //get the mainfile blob
            blockBlob.Delete(); //delete file
            blockBlob = container.GetBlockBlobReference(deleteHtmlFile); //get html file blob
            blockBlob.Delete(); //delete file
        }
        else if (fileType.Equals("read")) //if the string from reader is read, do this
        {
            string deleteMainFile = fileName + ".pdf"; //delete the main file
            container = blobClient.GetContainerReference("pdf-container"); //get container
            blockBlob = container.GetBlockBlobReference(deleteMainFile); //get the mainfile blob
            blockBlob.Delete(); //delete file
        }
        SqlQuery = "DELETE FROM videoTable where name ='" + fileName + "';"; //Delete the database entry
        cmd = new SqlCommand(SqlQuery, Connection); //establish new sqlcommand
        Reader = cmd.ExecuteReader(); //execture sql command set it to reader
        Connection.Close(); //close connection
        //EduLogger.logActivity(User.Identity.Name, "deleted content", HttpContext.Current.Request.Url.AbsoluteUri);
    }

    protected void OkButton_Click(object sender, EventArgs e)
    {
        string fileName = BlobUploader.FileName; //get filename of selected main file
        CloudBlobClient blobClient = (CloudBlobClient)Session["blobClient"];
        string type = TypeOfFileDropDownList.SelectedValue; //get the type of file from the dropdownlist
        CloudBlobContainer container = null;
        CloudBlockBlob blockBlob = null;
        string SqlQuery = "INSERT INTO videoTable VALUES('" + FileNameTextBox.Text + "','http://educenterstorage.blob.core.windows.net/images/" + fileName + ".img',"; //image container for the content image
        SqlQuery = SqlQuery + "'" + DescriptionTextBox.Text + "', '" + type + "','";


        /*
         * Get the container depending on which type of file it is, set the content type and updates the sql query with the blob location of
         * the video/pdf/audio
         */
        if (type.Equals("listen"))
        {
            container = blobClient.GetContainerReference("audio-container");
            blockBlob = container.GetBlockBlobReference(BlobUploader.FileName);
            blockBlob.Properties.ContentType = "application/octet-stream";
            SqlQuery = SqlQuery + "http://educenterstorage.blob.core.windows.net/audio-container/"; //container for audio container
    //        EduLogger.logActivity(User.Identity.Name, "added audio", HttpContext.Current.Request.Url.AbsoluteUri);
        }
        else if (type.Equals("watch"))
        {
            container = blobClient.GetContainerReference("video-container");
            blockBlob = container.GetBlockBlobReference(fileName);
            blockBlob.Properties.ContentType = "video/x-ms-wmv";
            SqlQuery = SqlQuery + "http://educenterstorage.blob.core.windows.net/video-container/"; //container for video content
    //        EduLogger.logActivity(User.Identity.Name, "added video", HttpContext.Current.Request.Url.AbsoluteUri);
        }
        else if (type.Equals("read"))
        {
            container = blobClient.GetContainerReference("pdf-container");
            blockBlob = container.GetBlockBlobReference(BlobUploader.FileName);
            SqlQuery = SqlQuery + "http://docs.google.com/gview?url=http://educenterstorage.blob.core.windows.net/pdf-container/"; //container for the pdf content
    //        EduLogger.logActivity(User.Identity.Name, "added pdf", HttpContext.Current.Request.Url.AbsoluteUri);
        }

        if (!type.Equals("read"))
        {
            SqlQuery = SqlQuery + HtmlUploader.FileName + "','"; //dont add html file if pdf
        }
        else if (type.Equals("read"))
        {
            SqlQuery = SqlQuery + BlobUploader.FileName + "','";
        }

        SqlQuery = SqlQuery + CategoryDropDownList.SelectedValue +"');";

        using (var fileStream = BlobUploader.FileContent) // Uploading the main file (Video, Audio or PDF)
        {
            blockBlob.UploadFromStream(fileStream);
        }

        if (!type.Equals("read"))
        {
            blockBlob = container.GetBlockBlobReference(HtmlUploader.FileName); //get a block reference for the HTML
            blockBlob.Properties.ContentType = "text/html";

            using (var fileStream = HtmlUploader.FileContent)
            {
                blockBlob.UploadFromStream(fileStream);
            }
        }

        container = blobClient.GetContainerReference("images"); //fixing container for the image
        blockBlob = container.GetBlockBlobReference(fileName + ".img");
        blockBlob.Properties.ContentType = "image/pjpeg";

        using (var fileStream = ImgUploader.FileContent) //uploading the images
        {
            blockBlob.UploadFromStream(fileStream);
        }
        ///////////////////////   END OF BLOB PART

        ///////////////////////   SQL PART
        string strConnString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection Connection = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand(SqlQuery, Connection);
        Connection.Open();  //open connection to database
        cmd.ExecuteNonQuery(); //execute the command
        Connection.Close(); //close connection to database
        ////////////////////// END OF SQL PART
    }
}